import { createStore } from 'vuex'
import { userApi } from '../api/user'

export default createStore({
    state: {
        user: null,
        token: localStorage.getItem('token') || null,
        userPreferences: null
    },
    
    mutations: {
        SET_USER(state, user) {
            state.user = user
        },
        SET_TOKEN(state, token) {
            state.token = token
            localStorage.setItem('token', token)
        },
        SET_USER_PREFERENCES(state, preferences) {
            state.userPreferences = preferences
        },
        CLEAR_AUTH(state) {
            state.user = null
            state.token = null
            state.userPreferences = null
            localStorage.removeItem('token')
        }
    },
    
    actions: {
        // 用户注册
        async register({ commit }, userData) {
            const response = await userApi.register(userData)
            commit('SET_TOKEN', response.access)
            commit('SET_USER', response.user)
            return response
        },
        
        // 用户登录
        async login({ commit }, credentials) {
            const response = await userApi.login(credentials)
            commit('SET_TOKEN', response.access)
            // 获取用户信息
            const userProfile = await userApi.getProfile()
            commit('SET_USER', userProfile)
            return response
        },
        
        // 获取用户信息
        async fetchUserProfile({ commit }) {
            const response = await userApi.getProfile()
            commit('SET_USER', response)
            return response
        },
        
        // 更新用户信息
        async updateProfile({ commit }, profileData) {
            const response = await userApi.updateProfile(profileData)
            commit('SET_USER', response)
            return response
        },
        
        // 获取用户偏好设置
        async fetchUserPreferences({ commit }) {
            const response = await userApi.getPreferences()
            commit('SET_USER_PREFERENCES', response)
            return response
        },
        
        // 更新用户偏好设置
        async updatePreferences({ commit }, preferencesData) {
            const response = await userApi.updatePreferences(preferencesData)
            commit('SET_USER_PREFERENCES', response)
            return response
        },
        
        // 登出
        logout({ commit }) {
            commit('CLEAR_AUTH')
        }
    },
    
    getters: {
        isAuthenticated: state => !!state.token,
        currentUser: state => state.user,
        userPreferences: state => state.userPreferences
    }
}) 